﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace CustomMapinfoWindows
{
    public static class ClickBehavior
    {
        public static DependencyProperty DoubleClickCommandProperty = DependencyProperty.RegisterAttached("DoubleClick",
                    typeof(ICommand),
                    typeof(ClickBehavior),
                    new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ClickBehavior.DoubleClickChanged)));

        public static void SetDoubleClick(DependencyObject target, ICommand value)
        {
            target.SetValue(ClickBehavior.DoubleClickCommandProperty, value);
        }

        private static void DoubleClickChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            UIElement element = target as UIElement;
            if (element != null)
            {
                // If we're putting in a new command and there wasn't one already
                // hook the event
                if ((e.NewValue != null) && (e.OldValue == null))
                {
                    element.MouseUp += element_MouseUp;
                }
                // If we're clearing the command and it wasn't already null
                // unhook the event
                else if ((e.NewValue == null) && (e.OldValue != null))
                {
                    element.MouseUp -= element_MouseUp;
                }
            }
        }

        static void element_MouseUp(object sender, MouseButtonEventArgs e)
        {

            UIElement element = (UIElement)sender;
            ICommand command = (ICommand)element.GetValue(ClickBehavior.DoubleClickCommandProperty);
            command.Execute(null);
        }
    }
}
